import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_module/beans/data_layer_bean.dart';
import 'package:flutter_module/beans/data_layer_item_bean.dart';
import 'package:flutter_module/data/data_manager.dart';
import 'package:flutter_module/data/ni_data_controller.dart';
import 'package:flutter_module/map/map_manager.dart';
import 'package:flutter_module/system/log_util.dart';
import 'package:flutter_module/viewModels/drawer_manager_viewmodel.dart';
import 'package:flutter_module/viewModels/map_control_viewmodel.dart';
import 'package:flutter_module/views/fragments/layers_manager_fragment.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:flutter_module/system/library_map.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../fragments/layer_edit_fragment.dart';

///地图顶部状态栏的适配器
class MapTitleBarAdapter {
  Widget? leading;
  Widget? titleWidget;
  String? title;
  List<Widget>? actions;

  MapTitleBarAdapter({
    this.leading,
    this.title,
    this.actions,
    this.titleWidget,
  }) {
    leading ??= Container();
    if (titleWidget == null) {
      if (title == null) {
        titleWidget = Container();
      } else {
        titleWidget = Text(title!);
      }
    }
    actions ??= [];
  }
}

///地图上方标题栏
class MapTitleBarWidget extends StatelessWidget {
  const MapTitleBarWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    LogUtil.instance.printf("顶部栏 创建");
    final DrawerManagerViewModel read = context.read<DrawerManagerViewModel>();
    read.initMapTitleBarContext(context);
    final NavigatorState _navigatorState = Navigator.of(context);

    return SizedBox(
      height: 120,
      child: Selector<DrawerManagerViewModel, MapTitleBarAdapter?>(
          selector: (context, model) => model.mapTitleBarAdapter,
          builder: (context, adapter, child) {
            LogUtil.instance.printf("顶部栏 更新");
            if (adapter == null) {
              return AppBar(
                titleTextStyle: const TextStyle(color: Colors.black),
                backgroundColor: const Color.fromARGB(200, 255, 255, 255),
                actions: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: IconButton(
                      color: Colors.black,
                      onPressed: () {
                        _navigatorState.push(MaterialPageRoute(builder: (context){
                          return const LayersManagerFragment();
                        }));
                      },
                      icon: const Icon(Icons.widgets),
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Icon(
                      Icons.search_off_outlined,
                      color: Colors.black,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8.0),
                    child: PopupMenuButton<int>(
                      itemBuilder: (context) {
                        return <PopupMenuEntry<int>>[
                          const PopupMenuItem<int>(
                            value: 0,
                            child: Text('创建图层'),
                          ),
                          const PopupMenuItem<int>(
                            value: 1,
                            child: Text('底图设置'),
                          ),
                          const PopupMenuItem<int>(
                            value: 2,
                            child: Text('离线地图'),
                          ),
                          const PopupMenuItem<int>(
                            value: 3,
                            child: Text('导入PBF'),
                          ),
                          const PopupMenuItem<int>(
                            value: 4,
                            child: Text('图例'),
                          ),
                          const PopupMenuItem<int>(
                            value: 5,
                            child: Text('测量'),
                          ),
                        ];
                      },
                      icon: const Icon(
                        Icons.more_horiz_outlined,
                        color: Colors.black,
                      ),
                      onSelected: (index) {
                        switch (index) {
                          case 0:
                            _navigatorState.push(MaterialPageRoute(
                                builder: (context) => LayerSettingFragment()));
                            // List<DataLayerItem> items = [];
                            // items.add(DataLayerItem(
                            //   key: "key1",
                            //   title: "名称",
                            //   nullable: false,
                            //   isMainName: true,
                            // ));
                            // items.add(DataLayerItem(
                            //   key: "key2",
                            //   title: "地址",
                            // ));
                            // items.add(DataLayerItem(
                            //   key: "key3",
                            //   title: "电话",
                            // ));
                            // DataLayer layer = DataLayer(
                            //     geometryType: GeometryType.geometryTypePoint,
                            //     layerName: "点图层1",
                            //     itemList: items);
                            //
                            // DataManager.instance.dataController
                            //     .createDataLayer(layer)
                            //     .then((value) => {
                            //           if (value == true)
                            //             {Fluttertoast.showToast(msg: "创建成功")}
                            //           else
                            //             {Fluttertoast.showToast(msg: "创建失败")}
                            //         });
                            break;
                          case 1:
                            read.createBaseMapSettingPage();
                            //Fluttertoast.showToast(msg: "底图设置");
                            break;
                          case 2:
                            Fluttertoast.showToast(msg: "离线地图");
                            break;
                          case 3:
                            Fluttertoast.showToast(msg: "导入PBF,长按进入多选模式");
                            // 打开本地文件选择器
                            Future<FilePickerResult?> future =
                                FilePicker.platform.pickFiles(
                                    allowMultiple:
                                        true /*, type: FileType.any, allowedExtensions: ["pbf"]*/);

                            future.then((result) {
                              if (result != null) {
                                List<String?> files = result.paths;
                                if (files.isEmpty) {
                                  Fluttertoast.showToast(msg: "没有选择任何PBF文件");
                                  return;
                                }
                                // 开始显示loading对话框
                                EasyLoading.show(status: '导入中...', maskType: EasyLoadingMaskType.black, dismissOnTap: false).whenComplete(() {
                                    // 将用户选中的pbf文件传递给native层
                                    DataManager.instance.dataController
                                        .importHdPbfData(files).then((value) => {
                                      if (value?["success"] ==
                                          true)
                                      {
                                        Fluttertoast.showToast(
                                            msg: "导入成功")
                                      }
                                      else
                                      {
                                        Fluttertoast.showToast(
                                            msg: "导入失败")
                                      }
                                    })
                                      .whenComplete(() => {
                                  // 结束时隐藏loading
                                  EasyLoading.dismiss()
                                  });
                                });

                              } else {
                                // User canceled the picker
                                Fluttertoast.showToast(msg: "取消选择PBF文件");
                              }
                            });
                            break;
                          case 4:
                            Fluttertoast.showToast(msg: "图例");
                            break;
                          case 5:
                            Fluttertoast.showToast(msg: "测量");
                            break;
                        }
                      },
                    ),
                  ),
                ],
                centerTitle: true,
                bottom: child == null ? const BottomBar() : child as BottomBar,
              );
            } else {
              return AppBar(
                titleTextStyle: const TextStyle(color: Colors.black),
                backgroundColor: const Color.fromARGB(200, 255, 255, 255),
                leading: adapter.leading,
                title: adapter.titleWidget,
                actions: adapter.actions,
                centerTitle: true,
                bottom: child == null ? const BottomBar() : child as BottomBar,
              );
            }
          },
          child: const BottomBar()),
    );
  }

  MapTitleBarAdapter _defaultAdapter() {
    return MapTitleBarAdapter();
  }
}

class BottomBar extends StatelessWidget implements PreferredSizeWidget {
  const BottomBar({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 8, bottom: 8),
      alignment: Alignment.center,
      child: Center(
        child: Selector<MapControlViewModel, BaiduLocation?>(
          selector: (context, model) => model.baiduLocation,
          builder: (context, location, child) {
            LogUtil.instance.printf("标题栏定位精度栏更新", tag: "Provider Selector");
            String txt = "";
            if (location?.locType != null) {
              switch (location?.locType) {
                case 161:
                  txt = "网络定位成功 精度范围${location?.radius}米";
                  break;
                case 61:
                  txt = "GPS定位成功 精度范围${location?.radius}米";
                  break;
              }
            }
            return Text(txt);
          },
          child: const Text(""),
        ),
      ),
      decoration: const BoxDecoration(
        border: Border(top: BorderSide(width: 1.0, color: Colors.grey)),
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(40.0);
}
